import React, { Component } from "react";
import './Todo.css';
import TodoHeader from "../TodoHeader/TodoHeader";
import TodoMain from "../TodoMain/TodoMain";
import TodoFooter from "../TodoFooter/TodoFooter";
import {nanoid} from 'nanoid';
export default class Todo extends Component {

    state = {
        todos: [
            {id: 1, title: '下午要帮同事搬家', done: false},
            {id: 2, title: '周末同事要结婚', done: false},
            {id: 3, title: '晚上要跟哥们开黑', done: true}
        ]
    }

    render() {
        return (
            <div className="todo-container">
                <div className="todo-wrap">
                    <TodoHeader />
                    <TodoMain
                         checkTodo={this.checkTodo} 
                          />
                    <TodoFooter 
                        checkAllTodo={this.checkAllTodo} 
                        todos={this.state.todos}
                        removeAllComTodos={this.removeAllComTodos}
                    />
                </div>
            </div>
        );
    }

    //声明一个方法
    addTodo = (title) => {
        //获取所有的 todo 任务
        let {todos, id} = this.state;
        //创建一个对象
        let todoObj = {
            id: nanoid(),  //
            title: title,
            done: false
        };
        //将对象压入到 todo 数组中
        let newArr = [...todos, todoObj];
        //设置修改状态
        this.setState({
            todos: newArr,
        })
    }

    //改变某一个任务的状态
    checkTodo = (id, status) => {
        //调用 map 方法
        let newArr = this.state.todos.map(item => {
            //判断
            if(item.id === id){
                //修改状态
                item.done = status;
            }
            return item;
        });
        //修改状态
        this.setState({
            todos: newArr
        })
    }

    //删除某一个任务
    removeTodo = (id) => {
        //移除数组中某一个元素
        let newArr = this.state.todos.filter(item => item.id !== id);
        console.log(newArr);
        //修改状态
        this.setState({
            todos: newArr
        })
    }

    //修改所有任务的状态
    checkAllTodo = (status) => {
        //修改所有任务的状态
        let newArr = this.state.todos.map(item => {
            //修改状态
            item.done = status;
            //返回
            return item;
        });
        //设置
        this.setState({
            todos: newArr
        })
    }

    //移除已经完成的任务
    removeAllComTodos = () => {
        //获取还没有完成的任务列表
        let newArr = this.state.todos.filter(item => !item.done);

        this.setState({
            todos: newArr
        });
    }

    componentDidMount(){
        //测试 addTodo
        // this.addTodo('123');

        //修改第一个任务为完成
        // this.checkTodo(3, false);

        //删除某一个任务
        // this.removeTodo(3);

        //测试修改所有任务的状态
        // this.checkAllTodo(false);

        //测试
        // this.removeAllComTodos();
    }

}
